var version = require('../models/version'),
    apiHandler = require('../services/api-handler'),
    userModel = require('../models/user');

exports.createNewVersion = function (req, res) {
    var newVersion = new version({
        "description": req.body.description,
        "name": req.body.name
    });
    version.createNewVersion(newVersion, apiHandler.handler.check(res, 'NO_VERSIONS', function (version) {
        apiHandler.setSuccessResponse(version, res);
    }));
};

exports.getAllVersions = function (req, res) {
    version.getAllVersion(req.body, apiHandler.handler.check(res, 'NO_VERSIONS', function (version) {
        apiHandler.setSuccessResponse(version, res);
    }));
};

exports.getVersioning = function (req, res) {
    version.getVersioning(req.body, apiHandler.handler.check(res, 'NO_VERSIONS', function (versions) {
        for (var i = 0; i < versions.length; i++) {
            versions[i].Total = (versions[i].male + versions[i].female);
        }
        apiHandler.setSuccessResponse(versions, res);
    }));
};

exports.changeLockStatus = function (req, res) {
    version.changeLockStatus(req.body.versionName, apiHandler.handler.check(res, 'NO_VERSIONS', function (versions) {
        apiHandler.setSuccessResponse(versions, res);
    }));
};

exports.assignRandomVersion = function (req, res) {
    var userId = req.user._id;
    if (!req.user.version) {
        version.assignRandomVersion(apiHandler.handler.check(res, 'NO_VERSIONS', function (versions) {
            userModel.getUserById(userId, apiHandler.handler.check(res, 'NO_USERS', function (user) {
                if (user.gender == "Male") {
                    versions[0].male = versions[0].male + 1;
                } else {
                    versions[0].female = versions[0].female + 1;
                }
                versions[0].save();
                user.version = versions[0].name;
                user.save();
                apiHandler.setSuccessResponse(user, res);
            }));
        }));
    } else {
        apiHandler.setErrorResponse('NO_USERS', res);
    }
};